package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.DrugLibrary;
import com.itheima.service.DrugLibraryService;

import com.itheima.untils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/drug")
public class DrugLibraryController {
    @Reference
    private DrugLibraryService drugLibraryService;

    @RequestMapping("/upload")
    public Result upload(@RequestParam(name = "excelFile") MultipartFile multipartFile){
        try {
            List<String[]> list = POIUtils.readExcel(multipartFile);
            List<DrugLibrary> drugLibraryList = new ArrayList<>();
            if(list!=null && list.size()>0){
                for (String[] strings : list) {
                    DrugLibrary drugLibrary = new DrugLibrary(null,strings[0],strings[1],strings[2]);
                    drugLibraryList.add(drugLibrary);
                }
                drugLibraryService.add(drugLibraryList);
            }else {
                throw new RuntimeException("表格数据转换失败!");
            }
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return drugLibraryService.findPage(queryPageBean);
    }
    @RequestMapping("/findAll")
    public Result findAll(){
        try {
            List<DrugLibrary> drugLibraryList = drugLibraryService.findAll();
            return new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS,drugLibraryList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_CHECKGROUP_FAIL);
        }
    }
    @RequestMapping("/insert")
    public Result insert(@RequestBody DrugLibrary drugLibrary){
        try {
            drugLibraryService.insert(drugLibrary);
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SETMEAL_SUCCESS);
        }
    }
}
